import { PiniaPluginContext } from "pinia";
import { StoreMap } from "@/tactics/store";

export function PersistedStoreSync(context: PiniaPluginContext) {
  const localStore = context.options?.localStore?.store === true;
  const sessionStore = context.options?.sessionStore?.store === true;

  if (!localStore && !sessionStore) return;
  let currentState = "{}";

  if (sessionStore) {
    currentState = StoreMap["sessionStorage"].getItem(context.store.$id) || "{}";
  } else if (localStore) {
    currentState = StoreMap["localStorage"].getItem(context.store.$id) || "{}";
  }

  try {
    context.store.$patch(JSON.parse(currentState));
  } catch (err) {
    console.error(`解析 ${context.store.$id} 存储数据失败`, err);
  }

  context.store.$subscribe(
    (_store, state) => {
      if (sessionStore) StoreMap["sessionStorage"].setItem(_store.storeId, JSON.stringify(state));
      if (localStore) StoreMap["localStorage"].setItem(_store.storeId, JSON.stringify(state));
    },
    {
      detached: true,
    },
  );
}
